#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* BuyLTNode(ListDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

bool LTEmpty(ListNode* phead)
{
	assert(phead);

	return phead->next == phead;
}

ListNode* LTInit()
{
	ListNode* head = BuyLTNode(-1);
	head->next = head;
	head->prev = head;

	return head;
}

void LTPushBack(ListNode* phead, ListDataType x)
{
	assert(phead);
	//ListNode* tail = phead->prev;
	//ListNode* newnode = BuyLTNode(x);
	//// tail  phead  newnode
	//tail->next = newnode;
	//newnode->prev = tail;
	//newnode->next = phead;
	//phead->prev = newnode;

	LTInsert(phead, x);

}

void LTPrint(ListNode* phead)
{
	
	ListNode* cur = phead->next;
	printf("<=head=>");
	while (cur != phead)
	{
		printf("%d<=>",cur->data);
		cur = cur->next;
	}

	printf("\n");
}

void LTPopBack(ListNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));
	ListNode* tail = phead->prev;
	ListNode* tailPrev = tail->prev;
	tailPrev->next = phead;
	phead->prev = tailPrev;
	free(tail);
	tail = NULL;
}

void LTPushFront(ListNode* phead, ListDataType x)
{
	assert(phead);
	//ListNode* newnode = BuyLTNode(x);
	//newnode->next = phead->next;
	//phead->next->prev = newnode;
	//phead->next = newnode;
	//newnode->prev = phead;

	LTInsert(phead->next,x);
}

void LTPopFront(ListNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));
	ListNode* head = phead->next;
	ListNode* headNext = head->next;
	headNext->prev = phead;
	phead->next = headNext;

	free(head);
	head = NULL;
}

void LTInsert(ListNode* pos, ListDataType x)
{
	assert(pos);
	ListNode* newnode = BuyLTNode(x);
	ListNode* prevPos = pos->prev;
	newnode->next = pos;
	pos->prev = newnode;
	newnode->prev = prevPos;
	prevPos->next = newnode;

}

ListNode* LTFindNode(ListNode* phead, ListDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;

		cur = cur->next;
	}
	return NULL;
}

void LTErase(ListNode* pos)
{
	assert(pos);
	assert(!LTEmpty(pos));
	ListNode* posPrev = pos->prev;
	ListNode* posNext = pos->next;
	posPrev->next = posNext;
	posNext->prev = posPrev;

	free(pos);
	pos = NULL;
}

void LTDestroy(ListNode** phead)
{
	assert(phead);
	ListNode* cur = (*phead)->next;
	ListNode* next = NULL;
	while (cur != (*phead))
	{
		next = cur->next;
		free(cur);
		cur = next;
	}
	free(*phead);
	*phead = NULL;
}